<template>
  <el-dialog
    v-model="dialogVisible"
    title="添加车辆信息"
    width="450"
    class="qc-custom-dialog"
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="110px"
      class="dialog-form-wrap"
    >
      <div class="drive-img" v-if="isOcr">
        <el-form-item
          label="证件照片"
          prop="drivingLicenseFront"
          class="img-front"
        >
          <QcUpload
            :valueModel="ruleForm.drivingLicenseFront"
            :url="URL_OCRUPLOAD"
            @on-success="handleSuccessFront"
            @before-upload="beforeUploadFront"
            @on-error="handleErrorFront"
            tip=""
            :size="10"
            title="请上传行驶证正本照片"
            :bodyData="{ side: 'face' }"
          ></QcUpload>
        </el-form-item>
        <el-form-item
          label=""
          prop="drivingLicenseAfter"
          label-width="0px"
          class="img-after"
        >
          <QcUpload
            :valueModel="ruleForm.drivingLicenseAfter"
            @on-success="handleSuccessAfter"
            @before-upload="beforeUploadAfter"
            @on-error="handleErrorAfter"
            tip=""
            :size="10"
            title="请上传行驶证副页照片"
            :bodyData="{ side: 'back' }"
          ></QcUpload>
        </el-form-item>
      </div>
      <el-form-item label="车牌号码" prop="plateNumber">
        <el-input
          v-model.trim="ruleForm.plateNumber"
          placeholder="请输入车牌号码"
          maxlength="30"
          clearable
          :disabled="comDisabled"
        />
      </el-form-item>
      <el-form-item label="车辆类型" prop="type">
        <el-input
          v-model.trim="ruleForm.type"
          placeholder="请输入车辆类型"
          maxlength="30"
          clearable
          :disabled="comDisabled"
        />
      </el-form-item>
      <el-form-item label="品牌型号" prop="model">
        <el-input
          v-model.trim="ruleForm.model"
          placeholder="请输入品牌型号"
          maxlength="30"
          clearable
          :disabled="comDisabled"
        />
      </el-form-item>
      <el-form-item label="车辆识别代码" prop="vin">
        <el-input
          v-model.trim="ruleForm.vin"
          placeholder="请输入车辆识别代码"
          maxlength="30"
          clearable
          :disabled="comDisabled"
        />
      </el-form-item>
      <el-form-item label="所有人" prop="owner">
        <el-input
          v-model.trim="ruleForm.owner"
          placeholder="请输入所有人"
          maxlength="30"
          clearable
          :disabled="comDisabled"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="hide">取消</el-button>
        <el-button type="primary" v-btnAntiShake="onSubmit"> 保存 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup name="dialog-car">
import QcUpload from '@/components/qcUpload/index.vue';
import type { FormInstance, FormRules } from 'element-plus';
import { checkUserNumber, queryIsSupportOcr } from '@/service/apis/user';
import { URL_OCRUPLOAD } from '@/service/apis/api';

interface Props {
  orgId?: any;
  channelId?: any;
  userId?: any;
}
const prop = withDefaults(defineProps<Props>(), {
  orgId: '',
  channelId: '',
  userId: '',
});

const ruleFormRef = ref<FormInstance>();

let dialogVisible = ref(false);
let index = ref(0);

interface CarInof {
  plateNumber: string;
  type: string;
  vin: string;
  owner: string;
  model: string;
  isDefault: boolean;
  drivingLicenseFront: string;
  drivingLicenseAfter: string;
}

let isOcr = ref(false);
let comDisabled = ref(false);

queryIsSupportOcr({}).then((res: any) => {
  isOcr.value = res === '1' ? true : false;
  comDisabled.value = isOcr.value;
});

let ruleForm = reactive<CarInof>({
  plateNumber: '',
  type: '',
  vin: '',
  owner: '',
  model: '',
  isDefault: true,
  drivingLicenseFront: '',
  drivingLicenseAfter: '',
});

let datas = reactive([] as any);

const checkNumber = (rule: any, value: any, callback: any) => {
  for (let i = 0; i < datas.length; i++) {
    const item = datas[i];
    if (item.plateNumber === value) {
      callback(new Error('车牌号码不能重复'));
      break;
    }
  }
  callback();
};
const checkVin = (rule: any, value: any, callback: any) => {
  for (let i = 0; i < datas.length; i++) {
    const item = datas[i];
    if (item.vin === value) {
      callback(new Error('车辆识别代码不能重复'));
      break;
    }
  }
  callback();
};

const errFront = ref('');
const checkFront = (rule: any, value: any, callback: any) => {
  if (!value) {
    if (errFront.value === 'type') {
      callback(new Error('上传的图片格式不正确'));
    } else if (errFront.value === 'size') {
      callback(new Error('上传的图片大于10M'));
    }
  }
  callback();
};
const errAfter = ref('');
const checkAfter = (rule: any, value: any, callback: any) => {
  if (!value) {
    if (errAfter.value === 'type') {
      callback(new Error('上传的图片格式不正确'));
    } else if (errAfter.value === 'size') {
      callback(new Error('上传的图片大于10M'));
    }
  }
  callback();
};
const rules = reactive<FormRules>({
  plateNumber: [
    { required: true, message: '请输入车牌号码', trigger: 'blur' },
    { validator: checkNumber, trigger: ['blur', 'change'] },
  ],
  type: [{ required: true, message: '请输入车辆类型', trigger: 'blur' }],
  vin: [
    { required: true, message: '请输入车辆识别代码', trigger: 'blur' },
    { validator: checkVin, trigger: ['blur', 'change'] },
  ],
  owner: [{ required: true, message: '请输入所有人', trigger: 'blur' }],
  model: [{ required: true, message: '请输入品牌型号', trigger: 'blur' }],
  drivingLicenseFront: [
    { required: true, message: '请上传行驶证正本照片', trigger: 'change' },
    { validator: checkFront, trigger: 'change' },
  ],
  drivingLicenseAfter: [
    { required: true, message: '请上传行驶证副本照片', trigger: 'change' },
    { validator: checkAfter, trigger: 'change' },
  ],
});

// 显示弹框
let row = reactive({} as any);
let isAdd = ref(true);
const show = (inx: number, com: any, data: any, form: CarInof) => {
  row = com;

  if (form) {
    datas = data.map((item: any, num: number) => num != inx);
    isAdd.value = false;
    ruleForm.plateNumber = form.plateNumber;
    ruleForm.type = form.type;
    ruleForm.vin = form.vin;
    ruleForm.model = form.model;
    ruleForm.owner = form.owner;
    ruleForm.isDefault = form.isDefault;
    if (isOcr.value) {
      ruleForm.drivingLicenseFront = form.drivingLicenseFront;
      ruleForm.drivingLicenseAfter = form.drivingLicenseAfter;
      comDisabled.value = false;
    }
  } else {
    datas = data;
    isAdd.value = true;
    ruleForm.plateNumber = '';
    ruleForm.type = '';
    ruleForm.vin = '';
    ruleForm.model = '';
    ruleForm.owner = '';
    ruleForm.isDefault = true;
    if (isOcr.value) {
      ruleForm.drivingLicenseFront = '';
      ruleForm.drivingLicenseAfter = '';
      comDisabled.value = true;
    }
  }

  dialogVisible.value = true;
  index.value = inx;
  ruleFormRef.value?.clearValidate();
};
// 关闭弹框
const hide = () => {
  dialogVisible.value = false;
};

const handleSuccessFront = (val: any) => {
  if (!val) {
    ElMessage({
      showClose: true,
      message: '行驶证正本照片识别失败，请重新上传！',
      type: 'warning',
    });
  }
  ruleForm.drivingLicenseFront = val.url || '';
  ruleForm.plateNumber = val.number || '';
  ruleForm.type = val.type || '';
  ruleForm.vin = val.vin || '';
  ruleForm.owner = val.owner || '';
  ruleForm.model = val.brand || '';
  comDisabled.value = !Boolean(val);
  ruleFormRef?.value?.validateField('drivingLicenseFront');
};
const handleErrorFront = () => {
  errFront.value = 'error';
  ruleFormRef?.value?.validateField('drivingLicenseFront');
};
const beforeUploadFront = (type: string) => {
  errFront.value = type;
  if (type) {
    ruleFormRef?.value?.validateField('drivingLicenseFront');
  }
};

const handleSuccessAfter = (val: any) => {
  ruleForm.drivingLicenseAfter = val;
  ruleFormRef?.value?.validateField('drivingLicenseAfter');
};
const handleErrorAfter = () => {
  errAfter.value = 'error';
  ruleFormRef?.value?.validateField('drivingLicenseAfter');
};
const beforeUploadAfter = (type: string) => {
  errAfter.value = type;
  if (type) {
    ruleFormRef?.value?.validateField('drivingLicenseAfter');
  }
};

const emit = defineEmits(['car-info']);

const onSubmit = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      // console.log('submit---', index, ruleForm, row, isAdd);
      const form: any = {
        plateNumber: ruleForm.plateNumber,
        type: ruleForm.type,
        vin: ruleForm.vin,
        owner: ruleForm.owner,
        model: ruleForm.model,
        isDefault: ruleForm.isDefault,
      };
      if (isOcr.value) {
        form.drivingLicenseFront = ruleForm.drivingLicenseFront;
        form.drivingLicenseAfter = ruleForm.drivingLicenseAfter;
      }
      let arr = [] as any;
      arr.push(form);
      let obj: any = {
        carDTOList: arr,
      };
      if (prop.orgId) {
        obj.orgId = prop.orgId;
      }
      if (prop.channelId) {
        obj.channelId = prop.channelId;
      }
      if (prop.userId) {
        obj.id = prop.userId;
      }
      checkUserNumber(obj).then((res: any) => {
        if (res === true) {
          emit('car-info', index.value, ruleForm, row, isAdd.value);
          hide();
        } else if (res === false) {
          ElMessageBox.confirm(
            '当前车辆已被其他用户绑定，您的操作会将前一个用户的车辆解绑，是否确认您的信息无误并提交？',
            '提示',
            {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning',
            }
          ).then(() => {
            emit('car-info', index.value, form, row, isAdd.value);
            hide();
          });
        } else {
        }
      });
    } else {
      console.log('error submit!', fields);
    }
  });
};

defineExpose({
  show,
});
</script>

<style lang="scss" scoped>
.drive-img {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;

  :deep(.edit-uploader) {
    display: flex;
    flex-direction: column;
  }
  :deep(.el-icon.edit-uploader-icon) {
    width: 132px;
    height: 76px;
  }
  :deep(.edit-uploader .el-upload .avatar) {
    width: 132px;
    height: 76px;
  }
  :deep(.el-icon.edit-close-icon) {
    left: 126px;
  }
  .img-front :deep(.el-icon.edit-uploader-icon) {
    background-image: url(@/assets/images/car-front.png);
    background-size: 100%;
  }
  .img-after :deep(.el-icon.edit-uploader-icon) {
    background-image: url(@/assets/images/car-after.png);
    background-size: 100%;
  }
}
</style>